/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedLineData, pickedVertexData } from '@amcax/base';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { omitBy } from 'lodash';
import { useEffect, useMemo, useState } from 'react';
import { usePlaneContext } from './PlaneContext';
import { ChildPlaneCommandProps } from './types';

type CurveLocation = 'throughPoint' | 'ratio';

type FormData = {
  curve?: pickedLineData;
  location: CurveLocation; //穿越点、曲线比率两种方式  "throughPoint", "ratio"
  ratio?: number;
  point?: pickedVertexData;
};

type Params = {
  mode: 'normalCurve';
  curveLocation: CurveLocation;
  curve?: string;
  ratio?: number;
  isReverse?: boolean;
  points: string[];
};

// 创建平面-通过曲线的法平面
// 注：对于穿越点，我们这里实现为仅支持输入一个点，虽然接口使用点列表。
export const PlaneNormalCurve = ({
  props,
  onClose,
  editDxid,
}: ChildPlaneCommandProps) => {
  const [formData, setFormData] = useState<FormData>({
    location: 'throughPoint',
  });
  const { sharedCurve, setSharedCurve } = usePlaneContext();

  const { picker } = useTools();

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData({ location: 'throughPoint' });
      return;
    }

    const { curveLocation, curve, ratio, points } = props.params as Params;

    if (points === undefined) {
      await initEditDependency([curve]);
    } else {
      await initEditDependency([curve, ...points]);
    }

    const curveObj = picker.generatePickObjByPickID(curve) as pickedLineData;
    const point1 = points?.[0] ?? null;

    setFormData({
      location: curveLocation,
      curve: curveObj,
      ratio: ratio == null ? 0.0 : ratio,
      point:
        point1 != null
          ? (picker.generatePickObjByPickID(point1) as pickedVertexData)
          : null,
    });

    setSharedCurve(curveObj);
  }, [editDxid]);

  useEffect(() => {
    if (sharedCurve && !formData.curve) {
      setFormData((prev) => ({ ...prev, curve: sharedCurve }));
    }
  }, [sharedCurve]);

  const isFormDataValid = () => {
    const { curve } = formData;

    if (curve == null) {
      return false;
    }

    return true;
  };

  useAsyncEffect(async () => {
    if (!isFormDataValid()) {
      clear();
      return;
    }

    await execute(true);
  }, [formData]);

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, clear, confirmCommand, isLoading } =
    useCommand('cmd-plane-curve', {
      commandName: 'CreatePlane',
      editDxid,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const execute = (preview: boolean) => {
    const { curve, location, ratio, point } = formData;

    return confirmCommand(
      {
        a: {
          mode: 'normalCurve',
          curve: curve.edgeId,
          curveLocation: location,
          ratio: ratio,
          isReverse: curve?.assisObj.isReversed,
          points: point ? [point.vertexId] : [],
        },
      },
      preview,
    );
  };

  const schema: RJSFSchema = useMemo(() => {
    const properties = omitBy(
      {
        point:
          formData.location === 'throughPoint'
            ? {
                type: 'string',
                format: PickInputRJSFFormat.PickVertex,
              }
            : null,
        ratio:
          formData.location === 'ratio'
            ? {
                type: 'number',
                title: '比率',
                default: 0.0,
                multipleOf: 0.01,
                minimum: 0,
                maximum: 1,
              }
            : null,
      },
      (val) => val == null,
    );

    return {
      type: 'object',
      properties: {
        curve: {
          type: 'string',
          format: PickInputRJSFFormat.PickCurve,
        },
        location: {
          title: '位置',
          type: 'string',
          oneOf: [
            {
              type: 'string',
              title: '穿越点',
              const: 'throughPoint',
            },
            {
              type: 'number',
              title: '曲线比率',
              const: 'ratio',
            },
          ],
          default: 'throughPoint',
        },
        ...properties,
      },
    } as RJSFSchema;
  }, [formData.location]);

  return (
    <NonDialogPickableCommandForm
      className='-mt-3'
      disabled={initingEdit}
      onCancel={onClose}
      submitLoading={isLoading}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        if (v.curve && v.curve !== formData.curve) {
          setSharedCurve(v.curve);
        }

        setFormData(v);
      }}
      extraUiSchema={{
        curve: {
          'ui:placeholder': '请输入曲线',
          'ui:autofocus': true,
          'ui:options': {
            showArrow: true,
            curveReversable: true,
          },
        },
        point: {
          'ui:placeholder': '请输入点(默认为曲线的中点)',
        },
        ratio: {
          'ui:placeholder': '请输入比率',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
};
